package de.le.mfw.client.main.view;

import com.google.gwt.user.client.ui.Widget;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.events.HasClickHandlers;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.HeaderItem;
import com.smartgwt.client.widgets.form.fields.PasswordItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.validator.MatchesFieldValidator;
import com.smartgwt.client.widgets.layout.VLayout;

import de.le.mfw.client.main.presenter.SettingsPresenter.SettingsView;
import de.le.mfw.client.main.view.validator.EmailValidator;
import de.le.mfw.client.main.view.validator.MinLengthValidator;

public class SettingsViewImpl implements SettingsView {

	private DynamicForm form = new DynamicForm();
	private IButton saveButton = new IButton("Speichern");

	public Widget asWidget() {
		VLayout layout = new VLayout();
		layout.setWidth(250);
		layout.setMembersMargin(5);
		layout.setLayoutMargin(10);

		form = createForm();
		layout.addMember(form);

		saveButton.setWidth100();
		layout.addMember(saveButton);

		return layout;
	}

	private DynamicForm createForm() {
		HeaderItem header = new HeaderItem();
		header.setDefaultValue("Benutzereinstellungen");

		TextItem emailField = new TextItem();
		emailField.setName("email");
		emailField.setTitle("Email");
		emailField.setValidators(new EmailValidator());

		PasswordItem passwordField = new PasswordItem();
		passwordField.setName("password");
		passwordField.setTitle("Passwort");
		passwordField.setValidators(new MinLengthValidator(8));

		PasswordItem passwordField2 = new PasswordItem();
		passwordField2.setName("password2");
		passwordField2.setTitle("Passwort (Wdh.)");

		MatchesFieldValidator matchesValidator = new MatchesFieldValidator();
		matchesValidator.setOtherField("password");
		matchesValidator.setErrorMessage("Passwörter stimmen nicht überein");
		passwordField2.setValidators(matchesValidator);

		form.setFields(header, emailField, passwordField, passwordField2);
		form.setWidth100();
		form.draw();
		return form;
	}

	public boolean isValid() {
		return form.validate();
	}

	public HasClickHandlers getSaveButton() {
		return saveButton;
	}

	public String getEmail() {
		return (String) form.getValue("email");
	}

	public String getPassword() {
		return (String) form.getValue("password");
	}

	public void setEmail(String email) {
		form.setValue("email", email);
	}
}
